/********************************************
 * Copyright (c) 2022
 * All rights reserved.
 *
 * 文件名称：callback.c
 * 摘 要：回调函数
 *
 * 当前版本：1.0
 * 作 者：任慧
 * 完成日期：2022年7月23日
 *
 * ********************************************/

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

#include "zlog.h"
#include "data_sq.h"
#include "mqtt_conf.h"
#include "mosquitto.h"
#include "sqlite3.h"
#include "iniparser.h"
#include "dictionary.h"

void my_connect_callback(struct mosquitto *mosq,void *obj,int rc)
{

        mqtt_t                     *mqtt_ctx = (mqtt_t *)obj;

        if (0 != rc)
        {
                zlog_error(mqtt_ctx->c,"connect failure%s",strerror(errno));
                return;
        }

        if(mosquitto_subscribe(mosq,NULL,mqtt_ctx->topic,0) != MOSQ_ERR_SUCCESS)
        {
                zlog_error(mqtt_ctx->c,"subscribe failure:%s",strerror(errno));
                return;
        }

	return;
}

void my_disconnect_callback(struct mosquitto *mosq,void *obj,int rc)
{
        mqtt_t                     *mqtt_ctx = (mqtt_t *)obj;

        if(rc == 0)
        {
                zlog_error(mqtt_ctx->c,"client get disconnected");
        }
        else{
                zlog_notice(mqtt_ctx->c,"rc = %d\n",rc);
                zlog_notice(mqtt_ctx->c,"Error disconnect:%s",strerror(errno));
        }
	return;
}

void my_subscribe_callback(struct mosquitto *mosq,void *obj,int mid,int qos_count,const int *granted_qos)
{
        mqtt_t                     *mqtt_ctx = (mqtt_t *)obj;

        zlog_info(mqtt_ctx->c,"subcribe successfully");
}


void my_message_callback(struct mosquitto *mosq,void *obj,const struct mosquitto_message *message)
{
        mqtt_t                     *mqtt_ctx = (mqtt_t *)obj;
        sqlite3       *db;
        db = create_database();
        if(db == NULL)
        {
                zlog_error(mqtt_ctx->c,"create database failure%s",strerror(errno));
                return;
        }

        zlog_info(mqtt_ctx->c,"%s",message->payload);

        if(insert_data(message->payload,db) < 0)
        {
                zlog_error(mqtt_ctx->c,"back up data into database failure:%s",strerror(errno));
		close_database(db);
                return;
        }
        zlog_info(mqtt_ctx->c,"back up data to database successfully!");
	close_database(db);

}

